#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
配置管理器 - 提升程序拓展性
"""

import json
import os
from typing import Dict, Any, Optional
from datetime import datetime

class ConfigManager:
    """
    配置管理器
    
    负责管理程序的所有配置，包括：
    - 分类规则
    - 用户设置
    - 平台配置
    - 系统参数
    """
    
    def __init__(self, config_dir: str = "config"):
        """
        初始化配置管理器
        
        Args:
            config_dir: 配置文件目录
        """
        self.config_dir = config_dir
        self.ensure_config_dir()
        
        # 配置文件路径
        self.classification_rules_file = os.path.join(config_dir, "classification_rules.json")
        self.user_settings_file = os.path.join(config_dir, "user_settings.json")
        self.platform_config_file = os.path.join(config_dir, "platform_config.json")
        self.system_config_file = os.path.join(config_dir, "system_config.json")
        
        # 加载配置
        self.classification_rules = self.load_classification_rules()
        self.user_settings = self.load_user_settings()
        self.platform_config = self.load_platform_config()
        self.system_config = self.load_system_config()
    
    def ensure_config_dir(self):
        """确保配置目录存在"""
        if not os.path.exists(self.config_dir):
            os.makedirs(self.config_dir)
    
    def load_classification_rules(self) -> Dict[str, Any]:
        """加载分类规则"""
        if os.path.exists(self.classification_rules_file):
            try:
                with open(self.classification_rules_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except Exception as e:
                print(f"加载分类规则失败: {e}")
        
        # 返回默认分类规则
        return self.get_default_classification_rules()
    
    def load_user_settings(self) -> Dict[str, Any]:
        """加载用户设置"""
        if os.path.exists(self.user_settings_file):
            try:
                with open(self.user_settings_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except Exception as e:
                print(f"加载用户设置失败: {e}")
        
        return self.get_default_user_settings()
    
    def load_platform_config(self) -> Dict[str, Any]:
        """加载平台配置"""
        if os.path.exists(self.platform_config_file):
            try:
                with open(self.platform_config_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except Exception as e:
                print(f"加载平台配置失败: {e}")
        
        return self.get_default_platform_config()
    
    def load_system_config(self) -> Dict[str, Any]:
        """加载系统配置"""
        if os.path.exists(self.system_config_file):
            try:
                with open(self.system_config_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except Exception as e:
                print(f"加载系统配置失败: {e}")
        
        return self.get_default_system_config()
    
    def save_classification_rules(self, rules: Dict[str, Any]):
        """保存分类规则"""
        try:
            with open(self.classification_rules_file, 'w', encoding='utf-8') as f:
                json.dump(rules, f, ensure_ascii=False, indent=2)
            self.classification_rules = rules
            print("分类规则保存成功")
        except Exception as e:
            print(f"保存分类规则失败: {e}")
    
    def save_user_settings(self, settings: Dict[str, Any]):
        """保存用户设置"""
        try:
            with open(self.user_settings_file, 'w', encoding='utf-8') as f:
                json.dump(settings, f, ensure_ascii=False, indent=2)
            self.user_settings = settings
            print("用户设置保存成功")
        except Exception as e:
            print(f"保存用户设置失败: {e}")
    
    def get_default_classification_rules(self) -> Dict[str, Any]:
        """获取默认分类规则"""
        return {
            "description": "默认分类规则",
            "version": "1.0.0",
            "last_updated": datetime.now().isoformat(),
            "rules": {
                "营业收入": {
                    "主营业务收入": ["工资", "薪资", "月薪", "奖金", "绩效"],
                    "其他业务收入": ["兼职", "副业", "咨询", "服务"],
                    "投资收益": ["余额宝", "基金", "理财", "投资", "股票", "证券"],
                    "被动收入": ["租金", "房租", "分红", "股息"],
                    "意外收入": ["红包", "奖励", "退款", "返还", "淘宝", "签到"]
                },
                "营业总支出": {
                    "管理费用": ["房租", "水费", "电费", "燃气", "手机", "话费", "网络", "宽带", "保险", "医疗", "医院", "税费", "培训", "课程", "学习", "书籍"],
                    "销售费用": ["外卖", "餐饮", "餐厅", "超市", "购物", "打车", "交通", "地铁", "公交", "加油", "游戏", "电影", "娱乐", "服装", "衣服", "数码", "电子", "旅游", "份子钱", "随礼"],
                    "财务费用": ["利息", "手续费", "财务", "花呗", "还款"],
                    "其他费用": ["随礼", "份子钱", "罚款"]
                }
            }
        }
    
    def get_default_user_settings(self) -> Dict[str, Any]:
        """获取默认用户设置"""
        return {
            "display_settings": {
                "default_records_per_page": 10,
                "date_format": "%Y-%m-%d",
                "currency_symbol": "¥",
                "show_original_category": True
            },
            "export_settings": {
                "default_format": "excel",
                "include_charts": True,
                "include_summary": True
            },
            "classification_settings": {
                "auto_classify": True,
                "confidence_threshold": 0.8,
                "use_machine_learning": False
            }
        }
    
    def get_default_platform_config(self) -> Dict[str, Any]:
        """获取默认平台配置"""
        return {
            "supported_platforms": {
                "alipay": {
                    "name": "支付宝",
                    "file_types": [".csv"],
                    "encoding": "gbk",
                    "header_row": 25,
                    "enabled": True
                },
                "wechat": {
                    "name": "微信",
                    "file_types": [".xlsx"],
                    "encoding": "utf-8",
                    "header_row": 16,
                    "enabled": True
                },
                "jd": {
                    "name": "京东",
                    "file_types": [".csv", ".xlsx"],
                    "encoding": "utf-8",
                    "header_row": 1,
                    "enabled": False
                },
                "unionpay": {
                    "name": "云闪付",
                    "file_types": [".csv"],
                    "encoding": "utf-8",
                    "header_row": 1,
                    "enabled": False
                }
            }
        }
    
    def get_default_system_config(self) -> Dict[str, Any]:
        """获取默认系统配置"""
        return {
            "performance": {
                "max_records_per_batch": 1000,
                "cache_size": 100,
                "parallel_processing": True
            },
            "logging": {
                "level": "INFO",
                "file": "logs/bill_analyzer.log",
                "max_size": "10MB",
                "backup_count": 5
            },
            "security": {
                "encrypt_sensitive_data": False,
                "data_retention_days": 365,
                "backup_enabled": True
            }
        }
    
    def add_platform(self, platform_name: str, config: Dict[str, Any]):
        """添加新平台配置"""
        self.platform_config["supported_platforms"][platform_name] = config
        self.save_platform_config()
    
    def update_classification_rule(self, level1: str, level2: str, keywords: list):
        """更新分类规则"""
        if level1 not in self.classification_rules["rules"]:
            self.classification_rules["rules"][level1] = {}
        
        self.classification_rules["rules"][level1][level2] = keywords
        self.classification_rules["last_updated"] = datetime.now().isoformat()
        self.save_classification_rules(self.classification_rules)
    
    def save_platform_config(self):
        """保存平台配置"""
        try:
            with open(self.platform_config_file, 'w', encoding='utf-8') as f:
                json.dump(self.platform_config, f, ensure_ascii=False, indent=2)
            print("平台配置保存成功")
        except Exception as e:
            print(f"保存平台配置失败: {e}")
    
    def get_platform_config(self, platform_name: str) -> Optional[Dict[str, Any]]:
        """获取指定平台配置"""
        return self.platform_config["supported_platforms"].get(platform_name)
    
    def is_platform_enabled(self, platform_name: str) -> bool:
        """检查平台是否启用"""
        platform = self.get_platform_config(platform_name)
        return platform and platform.get("enabled", False)
    
    def get_classification_keywords(self, level1: str, level2: str) -> list:
        """获取分类关键词"""
        return self.classification_rules["rules"].get(level1, {}).get(level2, [])
    
    def add_classification_keyword(self, level1: str, level2: str, keyword: str):
        """添加分类关键词"""
        if level1 not in self.classification_rules["rules"]:
            self.classification_rules["rules"][level1] = {}
        
        if level2 not in self.classification_rules["rules"][level1]:
            self.classification_rules["rules"][level1][level2] = []
        
        if keyword not in self.classification_rules["rules"][level1][level2]:
            self.classification_rules["rules"][level1][level2].append(keyword)
            self.classification_rules["last_updated"] = datetime.now().isoformat()
            self.save_classification_rules(self.classification_rules)
            print(f"关键词 '{keyword}' 已添加到 {level1} > {level2}")
        else:
            print(f"关键词 '{keyword}' 已存在")

# 使用示例
if __name__ == "__main__":
    # 创建配置管理器
    config = ConfigManager()
    
    # 添加新平台
    config.add_platform("jd", {
        "name": "京东",
        "file_types": [".csv", ".xlsx"],
        "encoding": "utf-8",
        "header_row": 1,
        "enabled": True
    })
    
    # 更新分类规则
    config.update_classification_rule("营业收入", "投资收益", ["余额宝", "基金", "理财"])
    
    # 添加关键词
    config.add_classification_keyword("营业总支出", "销售费用", "网购")
    
    print("配置管理器测试完成！")
